const { writeFile, appendFile } = require('fs/promises')
const  chokidar = require('chokidar')
const { getClass, createCss, getConfig } = require('../uitls')
const Css = require('../css')

let classData = []
let inArr = (i)=>{
	if(classData.includes(i)) return false
	classData.push(i)
	return true
}
const cssFn = () =>{
	let { input, output, persistent } = getConfig()
	let watch = chokidar.watch(input, {persistent})
	watch.on('all', async (env, path)=>{
		if(env==='add' || env==='change'){
			let classArr = await getClass(path)
			let strData = classArr.join(' ')
			// classArr = classArr.filter(inArr).map(createCss).filter(i=>i)
			let cssData = Object.keys(Css).map(i => Css[i](strData)).filter(i=>i).join('\n')
			if (classData.length === 0) {
				await writeFile(output, cssData)
			} else{
				await appendFile(output, cssData)
			}
			
			console.log(cssData);
		}
	})
}

module.exports = cssFn